package com.yootoo.extpmml.smg3.loader;

import com.experian.stratman.decisionagent.business.IStrategyLoader;
import com.experian.stratman.decisionagent.runtime.DecisionAgentConfig;
import com.yootoo.extpmml.smg3.Smg3Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 缓存加载smg3策略包
 */
public class CacheStrategyLoader implements IStrategyLoader {
    private static final Logger logger = LoggerFactory.getLogger(CacheStrategyLoader.class);

    private static final String STRATEGY_STRAT_PATH = "strategy.path";

    @Override
    public InputStream getStream(String strategyName) throws RuntimeException, IOException {
        if(strategyName.endsWith("ser")){
            if(strategyName.startsWith("/")){
                strategyName = strategyName.substring(1).split("\\.",-1)[0];
            }
            if (!Smg3Cache.cache.containsKey(strategyName)){
                throw new RuntimeException(strategyName + " not exists in cache");
            }
            String strategyPath = DecisionAgentConfig.instance().getProperty(STRATEGY_STRAT_PATH);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(strategyPath, strategyName + ".ser"));
            fileOutputStream.write(Smg3Cache.cache.get(strategyName).getPmml());
            fileOutputStream.close();
            logger.info("读取ser包成功");
            return new FileInputStream(new File(strategyPath,strategyName + ".ser"));

        }else {
            throw new FileNotFoundException("File not found in all configured directories");
        }
    }


}
